package com.aurora.app.interceptor;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.aurora.app.constant.Conf;
import com.aurora.app.entity.User;
import com.aurora.app.entity.WeixinAppToken;
import com.aurora.app.entity.WeixinUserToken;
import com.aurora.app.service.UserService;
import com.aurora.app.service.WeixinAppTokenService;
import com.aurora.app.service.WeixinService;
import com.aurora.base.util.HTTPSRequest;

public class WeixinInterceptor extends HandlerInterceptorAdapter {
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	
	//获取用户code
	private final static String user_code_url= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";


	
	/**
	 * 实例化微信的业务类
	 */
	@Resource
	private WeixinService weixinService;
	@Resource
	private UserService userService;
	@Resource
	private WeixinAppTokenService weixinAppTokenService;
	/**
	 * 不包含的路径
	 */
	private List<String> excludeUrls;

	/**
	 * @return the excludeUrls
	 */
	public List<String> getExcludeUrls() {
		return this.excludeUrls;
	}

	/**
	 * @param excludeUrls
	 *            the excludeUrls to set
	 */
	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String requestPath = request.getRequestURI();
		requestPath = requestPath.substring(request.getContextPath().length());// 去掉项目路径
		for (String excludeUrl : this.excludeUrls) {
			if (requestPath.startsWith(excludeUrl)) {
				return true;
			}
		}
		
		LOG.info("--------------Starting login interceptor-----------");
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user != null){
			LOG.info("------------already login-----------------");
			return true;
		}else{
			LOG.info("------------log timeout or never login-----------------");
			WeixinAppToken weixinAppToken = this.weixinAppTokenService.findById(Conf.USED2_ID);
			if(weixinAppToken == null){
				LOG.info("------------weixin auth get error-----------------");
				return false;
			}else{
				//获取code
				String url ="";
				if(StringUtils.isNotBlank(request.getQueryString())){
				 url = requestPath + "?"+request.getQueryString();
				}else{
					 url = requestPath;
				}
				System.out.println(url);
				String requestUrl =  user_code_url.replaceAll("APPID",weixinAppToken.getAppId()).
						replaceAll("REDIRECT_URI","http://www.used2.cn/used2/api/weixin/login.do").
						replaceAll("SCOPE","snsapi_userinfo").
						replaceAll("STATE", url);
				LOG.info(requestUrl);
				response.sendRedirect(requestUrl);
				return false;
			}
		}
	}
}
